package com.apes.autoparts.supplier.contrast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.masterdata.model.AutoTimestamp;
import com.apes.autoparts.masterdata.repository.AutoTimestampRepository;
import com.apes.autoparts.supplier.platform.BusinessinfoSequence;
import com.apes.autoparts.supplier.platform.SupplierPlatformItem;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DistributedLock;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("contrastService")
public class ContrastService extends DomainService {

    @Autowired
    private ContrastDao contrastDao;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private AutoTimestampRepository timestampRepository;
    @Autowired
    private DistributedLock distributedLock;
    /***
     * 1. 通过平台供应商编码（流水码） + 平台原始码
     * 2. 供应商编码 + 商家编码（即商家OEM）
     */
    public JSONObject findOne(SupplierPlatformItem supplierPlatformItem, String partCode, String source) {

        JSONArray array = contrastDao.findOneContrastBySource(MapUtil.mapper(
                "SUPPLIER_PLATFORM_ITEM_ID", supplierPlatformItem.getId(),
                "SUPPLIER_PLATFORM_SOURCE", source
        ));
        if (array != null && array.size() != 0) return array.getJSONObject(0);
        return new JSONObject();
    }

    /***
     * 新增/修改（主要变更）
     * 1. 修改主数据
     * 2. 更新库存和不含税价格
     * 3. 修改对照信息
     */
    public void updateImportant(SimpleRequest request) {
        JSONObject param = request.getJO();
        param.put("ID", queryOrInsertBusinessInfo(param)); // 获取对应的供应商信息ID
        contrastDao.updateBusinessInfo(param);
        updateBusinessContrast(param);
    }



    /***
     * 修改 (非主要变更)
     * 1. 修改主数据
     * 2. 更新库存和不含税价格
     */
    public void updateUnImportant(SimpleRequest request) {
        JSONObject param = request.getJO();
        param.put("ID", queryOrInsertBusinessInfo(param)); // 获取对应的供应商信息ID

        contrastDao.updateBusinessInfo(param);
    }


    /***
     * 删除
     * 1. 状态改为下架
     */
    public void delete(SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONArray oneBusinessInfo = contrastDao.findOneBusinessInfo(param);
        if (oneBusinessInfo != null || oneBusinessInfo.size() == 0) return;
        param.put("ID", oneBusinessInfo.getJSONObject(0).getString("ID")); // 获取对应的供应商信息ID
        contrastDao.updateBusinessInfoOnshelves(param);
    }






    /***
     * 用于查询或者创建数据
     */
    private String queryOrInsertBusinessInfo(JSONObject param) {
        JSONArray array = contrastDao.findOneBusinessInfo(param);

        if (array == null || array.size() == 0) {
            Integer id = Integer.valueOf(sequenceService.getId(BusinessinfoSequence.CONST_TABLE_NAME));
            param.put("ID", id);
            array = contrastDao.createOneBusinessInfo(param);
        }

        return array.getJSONObject(0).getString("ID");
    }

    /***
     * 用于更新供应商对照
     */
    private void updateBusinessContrast(JSONObject param) {
        // 创建供应商对照数据
        JSONArray array = contrastDao.findOneBusinessContrast(param);
        if (array == null || array.size() == 0) array = contrastDao.createOneBusinessContrast(param);

        // 更新数据
        contrastDao.updateBusinessContrast(param);
    }

    public JSONArray queryInsertBusinessInfos(JSONObject param) {
        return contrastDao.findInsertBusinessInfos(param);
    }
    public void updateSupplierData(JSONObject param) {
        contrastDao.updateSupplierData(param);
    }

    public void createBusinessInfo(List createDate) {
        for (Object o : createDate) {
            JSONObject param = JSONObject.parseObject(o.toString()) ;
            Integer id = Integer.valueOf(sequenceService.getId(BusinessinfoSequence.CONST_TABLE_NAME));
            param.put("ID", id);
            contrastDao.createOneBusinessInfo(param);
            contrastDao.createOneBusinessContrast(param);
        }
    }

    public void updateBusinessInfoContrast(List updateData) {
        for (Object o : updateData) {
            JSONObject param = JSONObject.parseObject(o.toString()) ;
            contrastDao.updateBusinessInfo(param);
            contrastDao.updateBusinessContrast(param);
        }
    }

    public JSONArray getIncrementBusinessInfo(SimpleRequest request) {
        JSONObject jo = request.getJO();
        int PAGE = 0;
        jo.put("SIZE", 1000);
        jo.put("PAGE", PAGE);
        JSONArray businessinfos;
        while (true) {
            businessinfos = contrastDao.getBusinessinfoPage(jo);
            invoke("supplierPlatformTodo.MQDCSupplierCommodity", MapUtil.mapper("data", businessinfos));
            if (businessinfos.size() < 1000) {
                break;
            }
            PAGE++;
            jo.put("PAGE", PAGE);
        }
        return businessinfos;
    }

    /**
     * 定时获取数据供应商商品数据
     * @param request
     */
    public void getDCSupplierCommodityTask (SimpleRequest request) {

        String lockId = "DCSupplierCommodityTask";
        if(!distributedLock.lock(lockId, 90 * 60 * 1000)) {
            throw new RuntimeException("后台正在执行定时任务");
        }
        try {
            timedTaskSynDataCenterByConditions("auto.supplierPlatform.getIncrementBusinessInfo", "ID");
        } catch (Exception e) {
            distributedLock.unlock(lockId);
            throw new RuntimeException(e);
        }
        distributedLock.unlock(lockId);
    }

    /**
     *  获取供应商数据
     *
     * @param interfaceId
     * @return
     */
    public void timedTaskSynDataCenterByConditions(String interfaceId,String conditions) {
        // 取接口调用的时间戳
        AutoTimestamp timestamp = timestampRepository.findOne(interfaceId);
        Map data = new HashMap();
        data.put("interfaceMethod", interfaceId);
        if (timestamp != null) {
            data.put("TIMESTAMP", timestamp.getTime());
            data.put("conditions", timestamp.getConditions());
        } else {
            data.put("TIMESTAMP", LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + ".000000.000");
        }
        SimpleRequest simpleRequest = new SimpleRequest();
        simpleRequest.setData(data);
        JSONArray resultArray = getIncrementBusinessInfo(simpleRequest);
        // 更新最后的时间戳到 res_timestamp 表记录, 下次定时任务用
        if (resultArray.size() > 0) {
            // 获取最后的时间戳
            String lastTimeTamp = resultArray.getJSONObject(resultArray.size() - 1).getString("TS01");
            if (timestamp == null) {
                timestamp = new AutoTimestamp();
            }
            timestamp.setId(interfaceId);
            timestamp.setType("timestamp");
            timestamp.setConditions(resultArray.getJSONObject(resultArray.size() - 1).getString(conditions));
            timestamp.setTime(lastTimeTamp);
            timestampRepository.save(timestamp);
        }
    }

}
